"use strict";

const Service = require("egg").Service;
const OSS = require("ali-oss");
const STS = OSS.STS;
class OssService extends Service {
  // 获取oss文件上传token
  async getStsToken() {
    try {
      const client = new STS({
        accessKeyId: this.config.oss.accessKeyId,
        accessKeySecret: this.config.oss.accessKeySecret,
      });
      const res = await client.assumeRole(
        this.config.oss.roleArn,
        this.config.oss.policy,
        this.config.oss.tokenExpireTime
      );
      return this.ctx.helper.ormSuccess({
        accessKeyId: res.credentials.AccessKeyId,
        accessKeySecret: res.credentials.AccessKeySecret,
        stsToken: res.credentials.SecurityToken,
        region: this.config.oss.region,
        bucket: this.config.oss.bucketName,
        timeout: this.config.oss.tokenExpireTime,
        expiration: res.credentials.Expiration,
      });
    } catch (err) {
      return this.ctx.helper.ormError(err);
    }
  }

  /**
   * @description 删除oss图片
   * @param {*} ids 图片路径集合
   * @returns
   */
  async deleteOssImg(ids) {
    try {
      const client = new OSS({
        region: this.config.oss.region,
        accessKeyId: this.config.oss.accessKeyId,
        accessKeySecret: this.config.oss.accessKeySecret,
        bucket: this.config.oss.bucketName,
      });
      const res = await client.deleteMulti(ids, {
        quiet: true,
      });
      return this.ctx.helper.ormSuccess(res);
    } catch (err) {
      return this.ctx.helper.ormError(err);
    }
  }
}

module.exports = OssService;
